#define _GNU_SOURCE
#include "app_device.h"
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include "app_buffer.h"
#include "app_pool.h"
#include "app_mqtt.h"
#include "log/log.h"
#include "app_message.h"
#include "app_common.h"

static Device *device = NULL;
#define BUFFER_SIZE 1024
#define POOL_SIZE 10
#define INTERVAL_TIME_MS 200 //两次写入的最小间隔时间

Device *app_device_init(char *filename)
{
    if (device)
    {
        return device;
    }
    device = (Device *)malloc(sizeof(Device));
    device->filename = filename;
    device->fd = open(device->filename, O_RDWR);
    device->down_buffer = app_buffer_init(BUFFER_SIZE);
    device->up_buffer = app_buffer_init(BUFFER_SIZE);
    device->post_read = NULL;
    device->pre_write = NULL;
    device->is_running = 0;

    //初始化线程池
    app_pool_init(POOL_SIZE);
    // 初始化MQTT
    app_mqtt_init();
    return device;
}

//在线程池中某个分线程执行的任务函数
static int send_task_fun(void *arg)
{
    //从上行数据缓冲区中读取消息数据
    char data_buf[128];
    int len = app_buffer_read(device->up_buffer, data_buf, sizeof(data_buf));
    if (len <= 0)
    {
        log_debug("读取上行数据缓冲区失败");
        return -1;
    }
    
    //将字符数组消息转换成json消息
    char *json = app_message_chars2json(data_buf, len);

    //发送json消息给远程
    int ret = app_mqtt_send(json);
    if (ret == -1)
    {
        log_debug("发送json消息给远程失败");
        free(json);
        return -1;
    }
    log_debug("发送json消息给远程成功 : %s", json);
    free(json);
    return 0;
}

//不断读取串口数据的线程函数
static void *read_thread_fun(void *arg)
{ 
    while (device->is_running)  
    {
        // 从串口读取数据
        char data_buf[128];
        int len = read(device->fd, data_buf, sizeof(data_buf));
        if (len > 0 && device->post_read)
        {
            //将读取的数据处理成字符数组消息
            len = device->post_read(data_buf, len);
            if (len > 0)    
            {
                //将字符数组消息保存到上行缓冲区
                app_buffer_write(device->up_buffer, data_buf, len);
                //注册任务：将发送消息到远程的操作交给线程池
                app_pool_registerTask(send_task_fun, NULL);
            } 
        }
         
    }
}
//线程池某个线程执行
static int write_task_fun(void *arg)
{
    //从下行缓冲区中读取字符数组消息
    char data_buf[128];
    int len = app_buffer_read(device->down_buffer, data_buf, sizeof(data_buf));
    if (len <= 0) {
        //缓冲区没有消息
        log_error("读取下行缓冲区消息失败");
        return -1;
    }
    //将字符数消息转换成传输格式数据
    if(device->pre_write){
        len = device->pre_write(data_buf, len);
        
    }
    if(len > 0)
        {
            //如果没有达到200ms的时间间隔限制， 需要等待相差时间
            long interval_time = app_common_getCurrentTime() - device->last_write_time;
            if (interval_time < INTERVAL_TIME_MS)    
            {     
                usleep(INTERVAL_TIME_MS - interval_time);     
            }
            
            //将传输格式数据写入串口，发送下游设备
            int write_len = write(device->fd, data_buf, len);
            if (write_len != len)
            {
                log_error("写入串口失败");
                return -1;
            }
            //保存写入当前时间
            device->last_write_time = app_common_getCurrentTime();
            log_debug("写入串口发送数据成功: %s",app_common_chars2hexstr(data_buf, len));
            return 0;
        }
    return -1;
}
//接收远程消息的回调函数
static int receive_msg_callback(char *json)
{ 
    //将json消息转换为字符数组消息
    char data_buf[128];
    int len = app_message_json2chars(json, data_buf, sizeof(data_buf));
    //将字符数组消息写入设备下行缓冲区
    app_buffer_write(device->down_buffer, data_buf, len);
    //注册任务：将发送消息到远程的操作交给线程池
    app_pool_registerTask(write_task_fun, NULL);
    return 0;
}
int app_device_start(void)
{
    if (device->is_running)
    {
        log_debug("设备已经启动");
        return 0;
    }
    device->is_running = 1;
    pthread_create(&device->read_thread, NULL, read_thread_fun, NULL);  
    
    //注册接收远程消息的回调函数
    app_mqtt_registerRecvCallback(receive_msg_callback);
    return 0;
}

void app_device_destroy(void)
{
    close(device->fd);
    app_buffer_destroy(device->down_buffer);
    app_buffer_destroy(device->up_buffer);
    pthread_cancel(device->read_thread);
    device->is_running = 0;
    device->post_read = NULL;
    device->pre_write = NULL;
    app_pool_destroy();
    app_mqtt_close();
    free(device);
}
